package org.miniframework.mvc.render;

import org.miniframework.mvc.RequestProcessorChain;
import org.miniframework.mvc.type.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 页面视图渲染器
 */
public class ViewResultRender implements ResultRender{

    public static final String JSP_SOURCE_TEMPLATE = "/templates/";
    public static final String SUFFIX = ".jsp";
    private ModelAndView modelAndView;

    public ViewResultRender(Object result) {
        if (result instanceof ModelAndView){
            modelAndView = (ModelAndView) result;
        }else if (result instanceof String){
            // 返回的是视图
            modelAndView = new ModelAndView().setView((String) result);
        }else{
            throw new RuntimeException("illegal request result type");
        }
    }

    @Override
    public void render(RequestProcessorChain chain) throws Exception {
        HttpServletRequest request = chain.getRequest();
        HttpServletResponse response = chain.getResponse();
        Map<String, Object> viewData = modelAndView.getData();
        for (Map.Entry<String, Object> entry : viewData.entrySet()){
            request.setAttribute(entry.getKey(),entry.getValue());
        }
        request.getRequestDispatcher(JSP_SOURCE_TEMPLATE + modelAndView.getView() + SUFFIX).forward(request,response);
    }
}
